package com.lagou.serializer;

import com.lagou.request.RpcRequest;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageDecoder;

import java.util.List;

/**
 * @author wuyuhan
 * @date 2020/12/27 14:26
 */
public class RpcDecoder extends MessageToMessageDecoder<ByteBuf> {

    private Class<?> clazz;

    private Serializer serializer;



    public RpcDecoder(Class<?> clazz, Serializer serializer) {

        this.clazz = clazz;

        this.serializer = serializer;

    }

    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) throws Exception {
        //byte[] array = byteBuf.array();
        int length = byteBuf.readInt();
        byte[] bytes = new byte[length];
        byteBuf.readBytes(bytes);
        RpcRequest rpcRequest = (RpcRequest) serializer.deserialize(clazz, bytes);
        list.add(rpcRequest);
    }
}
